
package com.kweative.util;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author henrik
 */
public class KClassLoader {
    private static JarLoader cl = new JarLoader();

    public static Object getInstance(String name,String lib) {
        try {
            Class clazz = getClass(name,lib);
            if (clazz == null) return null;
            return clazz.newInstance();
        } catch (InstantiationException ex) {
            Logger.getLogger(KClassLoader.class.getName()).log(Level.SEVERE, String.format("Could not instantiate class: %s",name), ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(KClassLoader.class.getName()).log(Level.SEVERE, String.format("Access denied for class: %s",name), ex);
        }
        return null;
    }
    public static Object getInstance(String name) {
        return getInstance(name, null);
    }
    public static Class getClass(String name,String lib) {
        try {
            return Class.forName(name);
        } catch (ClassNotFoundException ex) {}
        
        if (lib != null) {
            try {
                cl.addURL(new URL("jar:file://" + lib + "!/"));
            } catch (MalformedURLException ex) {
                Logger.getLogger(KClassLoader.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        try {
            return cl.loadClass(name);
        } catch (ClassNotFoundException ex) {}
        
        Logger.getLogger(KClassLoader.class.getName()).log(Level.SEVERE, String.format("Class not found: %s",name));
        return null;
    }
    public static Class getClass(String name) {
        return getClass(name,null);
    }
    public static void loadJar(String path) {
        try {
            cl.addURL(new URL("jar:file://" + path + "!/"));
        } catch (MalformedURLException ex) {
            Logger.getLogger(KClassLoader.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static JarLoader getClassLoader() {
        return cl;
    }
}
